<?php
namespace App\Http\Controllers\Buz;

use App\Http\Controllers\Controller;
use App\Models\PasswordReset;
use App\Models\PlatUser;
use App\Models\PlatUserTmp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\Rule;
use Validator;

class AuthController extends Controller
{
    public function register()
    {

    }

    public function registerEmail(Request $request)
    {
        $credentials = $request->only('username');
        $tmp = PlatUserTmp::where($credentials)->first();
        $error = 0;
        if ( ! $tmp) {
            //throw exception
            $error = 1;
        }
        return view('buz.auth.register.register_email', compact('credentials', 'error'));
    }

    public function doRegister(Request $request)
    {
        $credentials = $request->only('token', 'username');

        $rule = [
            'username' => 'required|exists:plat_user_tmp',
            'token' => [
                'required',
                'max:32',
                Rule::exists('plat_user_tmp')->where(function ($query) {
                    $query->where('expired_at', '>', time());
                })
            ]
        ];
        $messages = [
            'username.required' => '注册username不能为空',
            'username.exists' => '注册username无效',
            'token.required' => '注册token不能为空',
            'token.max' => '注册token不符合规范',
            'token.exists' => '注册token无效'
        ];

        $validate = Validator::make($credentials, $rule, $messages);

        if ($validate->fails()) {
            return view('buz.auth.register.register_two', compact('credentials'))->withErrors($validate);
        }
        return view('buz.auth.register.register_two', compact('credentials'));
    }

    public function login()
    {

    }

    public function privacy()
    {
        $user = Session::get('user');
        return view('buz.member.mprivacy', compact('user'));
    }

    public function passwordReset(Request $request)
    {
        $credentials = $request->only('token', 'username');

        $rule = [
            'username' => 'required|exists:password_resets,email',
            'token' => [
                'required',
                'max:32',
                Rule::exists('password_resets')->where(function ($query) {
                    $query->where('expired_at', '>', time());
                })
            ]
        ];
        $messages = [
            'username.required' => '用户名不能为空',
            'username.exists' => '用户名无效',
            'token.required' => '修改token不能为空',
            'token.max' => '修改token不符合规范',
            'token.exists' => '修改token无效'
        ];

        $validate = Validator::make($credentials, $rule, $messages);
        if ($validate->fails()) {
            return view('buz.auth.forget.pwdUpdate', compact('credentials'))->withErrors($validate);
        }
        return view('buz.auth.forget.pwdUpdate', compact('credentials'));
    }
}
